/*
 * @Author: chengsl
 * @Date: 2022-11-03 18:59:58
 * @LastEditors: chengsl
 * @LastEditTime: 2022-12-02 11:06:36
 * @Description: 日志记录-后期准备将日志记录到本地文件里
 */
var fs = require('fs')
var { NOW_TIME, NOW_DATE } = require('../utils')
// const baseLogFilePath = `D:/git/gitee/node-server-project/log/logFile`
const baseLogFilePath = `./log/logFile`
class Logger {
  constructor({ fileName } = {}) {
    this.fileName = fileName
  }

  setFileName() {
    this.fileName = fileName
  }

  /**
   * 记录日志
   * @param {*} content 新增日志内容
   */
  info(content) {
    try {
      if(typeof content !== 'string') {
        content = JSON.stringify(content)
      }
      this.write(`${baseLogFilePath}/${NOW_DATE()}.log`, content)
    } catch (error) {
      console.log('记录日志运行出错:', error)
    }
  }
  
  // TODO
  error(content) {}

  /**
   * 写入内容
   * @param {*} file 文件路径
   * @param {*} content 要写入的新内容
   */
  write(file, content) {
    const newContent = `[${NOW_TIME()}]${this.fileName ? `[${this.fileName}]` : ''}: ${content}\n`
    console.log(newContent)
    fs.appendFile(file, newContent, function (err) {
      if (err) {
        return console.error('日志写入报错--', err)
      }
      // console.log('数据写入成功！')
    })
  }

  /**
   * 检查文件/文件夹是否存在
   * @param {*} path 文件/文件夹路径
   */
  checkHasFile(path) {
    return new Promise((resolve, reject) => {
      try {
        fs.exists(path, function (value) {
          resolve(value)
        })
      } catch (error) {
        reject(false)
      }
    })
  }
}
const logger = new Logger()
module.exports = {
  Logger,
  logger
}